package com.jus.player.activity.my;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_1;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_118;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_198;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_45;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_6;
import static com.jus.player.config.AppConfig.ProductInfo.PRODUCT_ID_DOLLAR_68;
import static com.jus.player.util.CommonUtils.findFromSp;
import static com.jus.player.util.CommonUtils.showToastAsync;
import static com.jus.player.util.CommonUtils.showToastPos;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.UserBean;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.OptimizedGooglePay;
import com.jus.player.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 充值页面
 */
public class RechargeActivity extends BaseActivity {

    // ------UI组件-----
    private ImageView rechargeBack;
    private LinearLayout dollar1, dollar6, dollar45, dollar68, dollar118, dollar198;
    private Button btnRechargeNow;
    private TextView balanceText;
    private ProgressBar loadingProgress;
    private LinearLayout rechargeDetail;
    private CommonUtils.ExchangeRateManager exchangeRateManager;
    // -----支付相关状态------
    private int selectedAmount = 0;
    private String selectedProductId = null;
    private View lastSelectedView = null;

    // -----并发控制-----
    private final AtomicBoolean isPaymentInProgress = new AtomicBoolean(false);
    // 使用AtomicInteger管理余额
    private final AtomicInteger balance = new AtomicInteger(0);
    // 使用线程池处理网络请求
    private static final ExecutorService PAYMENT_EXECUTOR = Executors.newCachedThreadPool();
    // 使用ConcurrentHashMap管理订单锁
    private static final ConcurrentHashMap<String, Object> orderLocks = new ConcurrentHashMap<>();

    // -----Google支付实例-----
    private OptimizedGooglePay googlePay;


    @Override
    protected int initLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView() {
        rechargeBack = findViewById(R.id.recharge_back);
        dollar1 = findViewById(R.id.dollar1);
        dollar6 = findViewById(R.id.dollar6);
        dollar45 = findViewById(R.id.dollar45);
        dollar68 = findViewById(R.id.dollar68);
        dollar118 = findViewById(R.id.dollar118);
        dollar198 = findViewById(R.id.dollar198);
        btnRechargeNow = findViewById(R.id.btn_recharge_now);
        balanceText = findViewById(R.id.balance_text);
        rechargeDetail = findViewById(R.id.recharge_detail);
        loadingProgress = findViewById(R.id.loadingProgress);
        initClickListeners();
    }

    @Override
    protected void initData() {
        // 初始化Google支付
        googlePay = new OptimizedGooglePay(this);
        googlePay.setPayCallback(this::handlePaymentResult);

        // 加载用户余额
        loadUserBalance();
        //加载商品实时金额
        getProductInfo();
    }

    private void getProductInfo() {
        TextView d1 = findViewById(R.id.d1);
        TextView d6 = findViewById(R.id.d6);
        TextView d45 = findViewById(R.id.d45);
        TextView d68 = findViewById(R.id.d68);
        TextView d118 = findViewById(R.id.d118);
        TextView d198 = findViewById(R.id.d198);

        //根据设备所在地区设置对应价格
        exchangeRateManager = new CommonUtils.ExchangeRateManager(this);
        d1.setText(exchangeRateManager.getLocalPrice(1));
        d6.setText(exchangeRateManager.getLocalPrice(6));
        d45.setText(exchangeRateManager.getLocalPrice(45));
        d68.setText(exchangeRateManager.getLocalPrice(68));
        d118.setText(exchangeRateManager.getLocalPrice(118));
        d198.setText(exchangeRateManager.getLocalPrice(198));

        //根据google play地区价格设置价格
        for (AppConfig.ProductInfo value : AppConfig.ProductInfo.values()) {
            googlePay.queryProductPrice(value.getId(), new OkHttpHelper.HttpCallback() {
                @Override
                public void onSuccess(String response) {
                    runOnUiThread(() -> {
                        switch (value) {
                            case PRODUCT_ID_DOLLAR_1:
                                d1.setText(response);
                                break;
                            case PRODUCT_ID_DOLLAR_6:
                                d6.setText(response);
                                break;
                            case PRODUCT_ID_DOLLAR_45:
                                d45.setText(response);
                                break;
                            case PRODUCT_ID_DOLLAR_68:
                                d68.setText(response);
                                break;
                            case PRODUCT_ID_DOLLAR_118:
                                d118.setText(response);
                                break;
                            case PRODUCT_ID_DOLLAR_198:
                                d198.setText(response);
                        }
                    });
                }

                @Override
                public void onFailure(OkHttpHelper.HttpException e) {

                }
            });
        }
    }

    private void initClickListeners() {
        rechargeBack.setOnClickListener(v -> finish());

        // 金额选择
        dollar1.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_1));
        dollar6.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_6));
        dollar45.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_45));
        dollar68.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_68));
        dollar118.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_118));
        dollar198.setOnClickListener(v -> selectAmount(v, PRODUCT_ID_DOLLAR_198));

        // 充值按钮
        btnRechargeNow.setOnClickListener(v -> {
            if (selectedProductId == null) {
                showToastPos(this, getString(R.string.hint_recharge_select), 300, false);
                return;
            }

            if (isPaymentInProgress.get()) {
                showToastPos(this, "正在处理支付，请稍候...", 300, false);
                return;
            }
            startPaymentProcess();
        });
        // 充值明细
        rechargeDetail.setOnClickListener(v -> {
            startActivity(new Intent(this, RechargeDetailActivity.class));
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查是否有未完成的支付
        googlePay.checkPendingPurchases();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (googlePay != null) {
            googlePay.destroy();
        }
    }

    // 金额选择处理
    private void selectAmount(View view, AppConfig.ProductInfo product) {
        if (lastSelectedView != null) {
            lastSelectedView.setBackgroundColor(ContextCompat.getColor(this, R.color.dollar_bg));
        }
        // 设置点击的按钮的背景颜色
        view.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow_start1));
        //view.setBackgroundResource(R.drawable.bg_my_vip);
        lastSelectedView = view;
        selectedAmount = (int) product.getPrice();
        selectedProductId = product.getId();

        // 更新UI显示选中的金额
        updateSelectedAmountUI((int) product.getPrice());
    }

    private void updateSelectedAmountUI(int amount) {
        String localPrice = exchangeRateManager.getLocalPrice(Double.valueOf(String.valueOf(amount)));
        String amountText = getString(R.string.recharge_amount_selected, localPrice);
        btnRechargeNow.setText(amountText);
    }

    // 开始支付流程
    private void startPaymentProcess() {
        isPaymentInProgress.set(true);
        //隐藏按钮
        setPaymentButtonState(true);
        CommonUtils.showLoading(this);
        createOrder();
    }

    /**
     * 请求网络接口：创建订单
     */
    private void createOrder() {
        PAYMENT_EXECUTOR.execute(() -> {
            Map<String, String> params = new HashMap<>();
            params.put("productId", selectedProductId);

            OkHttpHelper.getInstance(this).getAsync(ApiConfig.CREATE_ORDER, params,
                    new OkHttpHelper.HttpCallback() {
                        @Override
                        public void onSuccess(String response) {
                            JSONObject json = JSONObject.parseObject(response);
                            String orderId = json.getString(_DATA);
                            runOnUiThread(() -> googlePay.pay(orderId, selectedProductId));
                        }

                        @Override
                        public void onFailure(OkHttpHelper.HttpException e) {
                            runOnUiThread(() -> {
                                handlePaymentError(e.getMessage());
                            });
                        }
                    });
        });
    }

    // 处理支付结果
    private String handlePaymentResult(int payStatus, String orderCode) {
        runOnUiThread(() -> {
            switch (payStatus) {
                case AppConfig.PAY_OK:
                    handlePaymentSuccess(orderCode);
                    break;
                case AppConfig.PAY_FAILED:
                    handlePaymentFailure(orderCode, "支付失败");
                    break;
                case AppConfig.PAY_CANCEL:
                    handlePaymentFailure(orderCode, "支付已取消");
                    break;
                default:
                    handlePaymentFailure(orderCode, "未知支付状态");
            }
        });
        return getStatusMessage(payStatus);
    }

    private String getStatusMessage(int payStatus) {
        switch (payStatus) {
            case AppConfig.PAY_OK:
                return "充值成功 " + selectedAmount + " USD";
            case AppConfig.PAY_FAILED:
                return "充值失败";
            case AppConfig.PAY_CANCEL:
                return "您已取消支付";
            default:
                return "支付状态未知";
        }
    }

    private void handlePaymentSuccess(String orderCode) {
        // 更新本地余额
        int rechargeAmount = selectedAmount;
        if (selectedAmount >= 45) {
            //如果充值45$或以上F币翻倍
            rechargeAmount = selectedAmount * 2;
        }

        int newBalance = balance.addAndGet(rechargeAmount * 100);
        balanceText.setText(String.valueOf(newBalance));
        // 更新订单状态
        updateOrder(orderCode, rechargeAmount, AppConfig.INT_1);
        // 显示成功提示
        showToastPos(this, "充值成功!", 300, true);
        resetPaymentState();
    }

    private void handlePaymentFailure(String orderCode, String errorMsg) {
        // 更新订单状态
        updateOrder(orderCode, selectedAmount,
                errorMsg.contains("取消") ? AppConfig.INT_2 : AppConfig.INT_1_);
        // 显示错误提示
        showToastPos(this, errorMsg, 300, true);
        resetPaymentState();
    }


    private void handlePaymentError(String errorMsg) {
        CommonUtils.hideLoading(this);
        showToastPos(this, "创建订单失败: " + errorMsg, 300, false);
        resetPaymentState();
    }

    //设置支付状态
    private void resetPaymentState() {
        isPaymentInProgress.set(false);
        setPaymentButtonState(true);
        CommonUtils.hideLoading(this);
    }

    /**
     * 支付完成，更新订单状态
     */
    private void updateOrder(String orderCode, int amount, int status) {
        //获取订单专用锁
        Object lock;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            /*
             * 1.如果orderCode不存在，则执行lambda创建新Object作为value
             * 2.如果已存在，直接返回已存在的value，整个过程是原子性的
             */
            lock = orderLocks.computeIfAbsent(orderCode, k -> new Object());
        } else {
            // 传统方式实现相同功能
            synchronized (orderLocks) {
                lock = orderLocks.get(orderCode);
                if (lock == null) {
                    lock = new Object();
                    orderLocks.put(orderCode, lock);
                }
            }
        }
        synchronized (lock) {
            try {
                Map<String, String> params = new HashMap<>();
                params.put("orderCode", orderCode);
                params.put("price", String.valueOf(amount));
                params.put("purchaseState", String.valueOf(status));

                OkHttpHelper.getInstance(this).getAsync(ApiConfig.UPDATE_ORDER, params, new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String response) {
                        Log.d("RechargeActivity", "订单更新成功: " + orderCode);
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        Log.e("RechargeActivity", "订单更新失败: " + e.getMessage());
                        runOnUiThread(() -> showToastAsync(RechargeActivity.this, e.getMessage()));
                    }
                });
            } finally {
                orderLocks.remove(orderCode);
            }
        }
    }

    // 加载用户余额
    private void loadUserBalance() {
        OkHttpHelper.getInstance(this).getAsync(ApiConfig.MY_INFO, new HashMap<>(),
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject json = JSONObject.parseObject(response);
                        JSONObject userData = json.getJSONObject(_DATA);
                        UserBean user = JSON.to(UserBean.class, userData);

                        runOnUiThread(() -> {
                            if (user.getBalance() != null) {
                                balance.set(user.getBalance());
                                balanceText.setText(String.valueOf(user.getBalance()));
                            }
                        });
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        runOnUiThread(() -> {
                            showToastPos(RechargeActivity.this, "获取余额失败: " + e.getMessage(), 300, false);
                        });
                    }
                });
    }


    /**
     * 设置支付按钮状态
     *
     * @param enabled 是否启用按钮
     */
    private void setPaymentButtonState(boolean enabled) {

        btnRechargeNow.setVisibility(enabled ? View.VISIBLE : View.GONE);
        loadingProgress.setVisibility(enabled ? View.GONE : View.VISIBLE);
        btnRechargeNow.invalidate(); // 强制刷新视图
        btnRechargeNow.requestLayout(); // 请求重新布局

        btnRechargeNow.setEnabled(enabled);
        btnRechargeNow.setAlpha(enabled ? 1.0f : 0.5f);
    }


}